package com.ruoyi.web.controller.api;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ImgUpload;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdGererateFactory;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.IdWorker;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.vo.IndexGoodsVO;
import com.ruoyi.mall.domain.vo.MemberCollectVO;
import com.ruoyi.mall.service.*;
import com.ruoyi.web.AppBeanInjector;
import com.ruoyi.web.controller.utils.FBSStringUtil;
import com.ruoyi.web.controller.utils.WeixinUtils;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName ApiNewController
 * @Description 工具方法接口
 * @Author LCL
 * @Date 2022/02/24 10:17 AM
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api/timeArea")
@ResponseBody
public class ApiNewController {

    @Autowired
    private IMallTimeBannerService mallTimeBannerService;
    @Autowired
    private IMallTimeWarehouseService mallTimeWarehouseService;
    @Autowired
    private IMallMemberAddressService mallMemberAddressService;
    @Autowired
    private IMallTimeOrderService mallTimeOrderService;
    @Autowired
    private IMallTimeConfigService mallTimeConfigService;
    @Autowired
    private IMallDistributionConfigService mallDistributionConfigService;
    @Autowired
    private IMallMemberCouponService mallMemberCouponService;
    @Autowired
    private IMallTimeWithdrawService mallTimeWithdrawService;
//    @Autowired
//    private IdGererateFactory idGererateFactory;
    @Autowired
    private GeneratID generatID;
    @Autowired
    private IMallPayLogService mallPayLogService;

    /**
     * 抢购专区轮播图
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @return R.ok();
     */
    @GetMapping("/getTimeAreaBannerList")
    public ApiResult getTimeAreaBannerList(
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize) {
        try{
            MallTimeBanner mallTimeBanner = new MallTimeBanner();
            mallTimeBanner.setStatus("0");
            PageHelper.startPage(pageNum,pageSize);
            List<MallTimeBanner> mallTimeBannerList = mallTimeBannerService.selectMallTimeBannerList(mallTimeBanner);
            PageInfo<MallTimeBanner> pageInfo = new PageInfo<>(mallTimeBannerList);
            HashMap<String, Object> map = new HashMap<>();
            map.put("data", pageInfo);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 获取抢购专区模块
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param userId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getTimeAreaModular")
    public ApiResult getTimeAreaModular(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                        @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                        Long userId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        try{
            HashMap<String, Object> map = new HashMap<>();
            MallMemberUser user = mallMemberUserService.selectMallMemberUserById(userId);
            if (user == null) {
                return ApiResult.error("您的账号异常，请您联系客服。");
            } else if (user.getIsBlock() == 1) {
                return ApiResult.error("您的账号已被锁定，请您联系客服。");
            }  else if (user.getSignimgurl() == null || user.getSignimgurl().equals("")) {
                map.put("data", 0);// 上传用户签名图片
                return ApiResult.ok(map);// 提示阅读用户协议
            } else if (user.getAuditsignimgurl() == 2) {
                String tips = "您的签名审核被拒绝，原因："+user.getAuditsignimgurlremark();
                map.put("data", tips);
                return ApiResult.ok(map);// 提示上传签名
            } else {
                PageHelper.startPage(pageNum,pageSize);
                ArrayList<Object> list = new ArrayList<>();
                List<MallTimeWarehouse> mallTimeWarehouseList = mallTimeWarehouseService.selectMallTimeWarehouseList(new MallTimeWarehouse());
                for (MallTimeWarehouse MTW : mallTimeWarehouseList) {
                    String[] splitRegionId= user.getRegionId().split(",");// 用户可进区域
                    for (String regionId : splitRegionId) {
                        if (regionId.equals(MTW.getId().toString())) {
                            list.add(MTW);
                        }
                    }
                }
                PageInfo<Object> pageInfo = new PageInfo<>(list);
                map.put("data", pageInfo);
                return ApiResult.ok(map);
            }
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 获取用户协议等
     *
     * @return R.ok();
     */
    @GetMapping("/getUserAgreement")
    public ApiResult getUserAgreement() {
        try{
            List<MallTimeConfig> timeConfigs = mallTimeConfigService.selectMallTimeConfigList(new MallTimeConfig());
            HashMap<String, Object> map = new HashMap<>();
            map.put("data", timeConfigs.get(0));
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 上传签名
     *
     * @param params
     *      userId：用户ID
     *      signimgurl：签名图
     *
     * @return R.ok();
     */
    @PostMapping("/uploadSignature")
    public ApiResult uploadSignature(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("signimgurl")||StringUtils.isEmpty(params.get("signimgurl").toString())){
            return ApiResult.error("缺少签名图");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO != null) {
                userDO.setAuditsignimgurl(1);
                userDO.setSignimgurl(params.get("signimgurl").toString());
                userDO.setAuditsignimgurlremark("");
                mallMemberUserService.updateMallMemberUser(userDO);
            }
            return ApiResult.ok("上传成功");
        }catch (Exception e){
            return ApiResult.error("上传失败");
        }
    }

    @Autowired
    private IMallMemberUserService mallMemberUserService;
    @Autowired
    private IMallTimeGoodsService mallTimeGoodsService;

//    /**
//     * 进入抢购专区模块
//     *
//     * @param pageNum 页码
//     * @param pageSize 每页数据量
//     * @param userId：用户ID
//     * @param timeWarehouseId：抢购区ID
//     *
//     * @return R.ok();
//     */
//    @GetMapping("/enterTimeAreaModular")
//    public ApiResult enterTimeAreaModular(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
//                                          @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
//                                          Long userId, Long timeWarehouseId) {
//        if (userId == null) {
//            return ApiResult.error("缺少用户ID");
//        }
//        if (timeWarehouseId == null) {
//            return ApiResult.error("缺少抢购区ID");
//        }
//        try{
//            // 用户信息
//            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
//            // 抢购区域信息
//            MallTimeWarehouse mallTimeWarehouse = mallTimeWarehouseService.selectMallTimeWarehouseById(timeWarehouseId);
//            // 当前时分
//            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String dateNow = sd.format(new Date());
//            // 截取当前时间时分
//            int dateNowH = Integer.parseInt(dateNow.substring(11, 13));
//            int dateNowM = Integer.parseInt(dateNow.substring(14, 16));
//            // 截取开始时间时分
//            int dateStartH = Integer.parseInt(mallTimeWarehouse.getStartTime().substring(0, 2));
//            int dateStartM = Integer.parseInt(mallTimeWarehouse.getStartTime().substring(3, 5));
//            // 截取结束时间时分
//            int dateEndH = Integer.parseInt(mallTimeWarehouse.getEndTime().substring(0, 2));
//            int dateEndM = Integer.parseInt(mallTimeWarehouse.getEndTime().substring(3, 5));
//
//            if (memberUser == null) {
//                return ApiResult.error("用户异常");
//            } else if (memberUser.getIsBlock() == 1) {
//                return ApiResult.error("用户状态异常");// 拉黑
//            } else if (mallTimeWarehouse.getIsOpen()== 0) {
//                return ApiResult.error("该区域未开放");// 不开放
//            } else if (memberUser.getIsBlock() == 0) {
//                int isEnter = 0;
//                if (!memberUser.getRegionId().equals("0")) {
//                    String[] splitRegionId= memberUser.getRegionId().split(",");// 用户可进区域
//                    for (String regionId : splitRegionId) {
//                        if (regionId.equals(timeWarehouseId.toString())) {
//                            isEnter = 1;
//                            break;
//                        }
//                    }
//                } else {
//                    isEnter = 1;
//                }
//                if (isEnter == 0) {
//                    return ApiResult.error("用户不可进入");
//                } else if (memberUser.getExpires() != null && memberUser.getMinute() != 0) {
//                    if (memberUser.getExpires().getTime() >= new Date().getTime()) {
//                        if (memberUser.getMinute() > dateStartM) {
//                            int hour = 60 % memberUser.getMinute();
//                            if (hour == 0) {
//                                dateStartH = dateStartH - 1;
//                                dateStartM = 60 - memberUser.getMinute();
//                            } else {
//                                int minute = 60 / memberUser.getMinute();
//                                dateStartH = dateStartH - hour;
//                                dateStartM = 60 - minute;
//                            }
//                        } else {
//                            dateStartM = dateStartM - memberUser.getMinute();
//                        }
//                    }
//                }
//            }
//
//            int isData = 0;// 0-不能进 1-能进
//            // 当前小时数在开始和结束小时数之间
//            if (dateNowH >= dateStartH && dateNowH <= dateEndH) {
//                // 当前小时数大于开始小时数，当前小时数小于结束小时数
//                if (dateNowH > dateStartH && dateNowH < dateEndH) {
//                    isData = 1;
//                }
//                // 当前小时数等于开始小时数
//                if (dateNowH == dateStartH) {
//                    // 当前分钟数大于等于开始分钟数，当前分钟数小于等于结束分钟数
//                    if (dateNowM >= dateStartM && dateNowM <= dateEndM) {
//                        isData = 1;
//                    }
//                }
//                // 当前小时数等于结束小时数
//                if (dateNowH == dateEndH) {
//                    // 当前分钟数小于等于结束分钟数
//                    if (dateNowM <= dateEndM) {
//                        isData = 1;
//                    }
//                }
//            }
//
//            if (isData == 0) {
//                return ApiResult.error("未到时间");
//            } else {
//                MallTimeGoods mallTimeGoods = new MallTimeGoods();
//                mallTimeGoods.setRegionId(timeWarehouseId);
//                mallTimeGoods.setIsPublish(1);
//                PageHelper.startPage(pageNum,pageSize);
//                List<MallTimeGoods> timeGoodsList = mallTimeGoodsService.selectMallTimeGoodsList(mallTimeGoods);
//                PageInfo<MallTimeGoods> pageInfo = new PageInfo<>(timeGoodsList);
//                HashMap<String, Object> map = new HashMap<>();
//                map.put("data", pageInfo);
//                return ApiResult.ok(map);
//            }
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }

    /**
     * 进入抢购专区模块
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param userId：用户ID
     * @param timeWarehouseId：抢购区ID
     *
     * @return R.ok();
     */
    @GetMapping("/enterTimeAreaModular")
    public ApiResult enterTimeAreaModular(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                          @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                          Long userId, Long timeWarehouseId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        if (timeWarehouseId == null) {
            return ApiResult.error("缺少抢购区ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            // 抢购区域信息
            MallTimeWarehouse mallTimeWarehouse = mallTimeWarehouseService.selectMallTimeWarehouseById(timeWarehouseId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            } else if (memberUser.getIsBlock() == 1) {
                return ApiResult.error("您的账号已被锁定，请您联系客服。");// 拉黑
            } else if (mallTimeWarehouse.getIsOpen()== 0) {
                return ApiResult.error(mallTimeWarehouse.getTitle()+"等待开放");// 不开放
            } else {
                MallTimeGoods mallTimeGoods = new MallTimeGoods();
                mallTimeGoods.setRegionId(timeWarehouseId);
                mallTimeGoods.setIsPublish(1);
                PageHelper.startPage(pageNum,pageSize);
                List<MallTimeGoods> timeGoodsList = mallTimeGoodsService.selectIsPublishTimeGoodsList(mallTimeGoods);
                PageInfo<MallTimeGoods> pageInfo = new PageInfo<>(timeGoodsList);
                HashMap<String, Object> map = new HashMap<>();
                map.put("data", pageInfo);
                return ApiResult.ok(map);
            }
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 根据id查专区商品详情
     *
     * @param userId：用户ID
     * @param goodsId：商品ID
     *
     * @return R.ok();
     */
    @GetMapping("/getGoodsById")
    public ApiResult getGoodsById(Long userId, Long goodsId){
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        if (goodsId == null) {
            return ApiResult.error("缺少商品ID");
        }
        try {
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            // 商品信息
            MallTimeGoods timeGoods = mallTimeGoodsService.selectMallTimeGoodsById(goodsId);
            // 抢购区域信息
            MallTimeWarehouse timeWarehouse = mallTimeWarehouseService.selectMallTimeWarehouseById(timeGoods.getRegionId());

            if (memberUser == null || timeWarehouse == null) {
                return ApiResult.error("用户异常");
            } else if (memberUser.getIsBlock() == 1) {
                return ApiResult.error("您的账号已被锁定，请您联系客服。");// 拉黑
            } else if (timeWarehouse.getIsOpen()== 0) {
                return ApiResult.error("该区域暂未开放");// 不开放
            } else if (timeGoods.getIsPublish() == 0) {
                return ApiResult.error("该商品已抢完");// 已抢完
            } else if (memberUser.getIsBlock() == 0) {
                int isEnter = 0;
                if (!memberUser.getRegionId().equals("0")) {
                    String[] splitRegionId= memberUser.getRegionId().split(",");// 用户可进区域
                    for (String regionId : splitRegionId) {
                        if (regionId.equals(timeWarehouse.getId().toString())) {
                            isEnter = 1;
                            break;
                        }
                    }
                } else {
                    isEnter = 1;
                }
                if (isEnter == 0) {
                    return ApiResult.error("用户不可进入");
                }
            }
            MallTimeGoods goods = mallTimeGoodsService.selectMallTimeGoodsById(goodsId);
            if (goods != null) {
                MallMemberUser userById = mallMemberUserService.selectMallMemberUserById(timeGoods.getUserId());
                if (userById != null) {
                    goods.setUserName(userById.getName());
                    // 提前进入时间
                    // 截取开始时间时分
                    int dateStartH = Integer.parseInt(timeWarehouse.getStartTime().substring(0, 2));
                    int dateStartM = Integer.parseInt(timeWarehouse.getStartTime().substring(3, 5));
                    if (memberUser.getExpires() != null && memberUser.getMinute() != 0) {
                        if (memberUser.getExpires().getTime() >= new Date().getTime()) {
                            if (memberUser.getMinute() > dateStartM) {
                                int hour = 60 % memberUser.getMinute();
                                if (hour == 0) {
                                    dateStartH = dateStartH - 1;
                                    dateStartM = 60 - memberUser.getMinute();
                                } else {
                                    int minute = 60 / memberUser.getMinute();
                                    dateStartH = dateStartH - hour;
                                    dateStartM = 60 - minute;
                                }
                            } else {
                                dateStartM = dateStartM - memberUser.getMinute();
                            }
                        }
                        if (dateStartH >= 0 && dateStartH < 10) {
                            goods.setStartTime("0"+dateStartH+":"+dateStartM);
                        } else {
                            goods.setStartTime(dateStartH+":"+dateStartM);
                        }
                    } else {
                        goods.setStartTime(timeWarehouse.getStartTime());
                    }
                    goods.setEndTime(timeWarehouse.getEndTime());
                }
                return ApiResult.ok().put("data",goods);
            } else {
                return ApiResult.error("查无数据");
            }
        }catch (Exception e){
            return ApiResult.error("抢购失败");
        }
    }

    /**
     * 抢购
     *
     * @param params
     *      userId：用户ID
     *      goodsId：商品ID
     *      addressId：地址ID
     *
     * @return R.ok();
     */
    @PostMapping("/rushPurchase")
    public ApiResult rushPurchase(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("goodsId")||StringUtils.isEmpty(params.get("goodsId").toString())){
            return ApiResult.error("缺少商品ID");
        }
        if (!params.containsKey("addressId")||StringUtils.isEmpty(params.get("addressId").toString())){
            return ApiResult.error("缺少收货地址ID");
        }
        try {
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            // 收货信息
            MallMemberAddress memberAddress = mallMemberAddressService.selectMallMemberAddressById(Long.valueOf(params.get("addressId").toString()));
            if (memberAddress == null) {
                return ApiResult.error("请先完善收货信息");
            }
//            if (memberUser.getAlipayCode() == null && memberUser.getWxCode() == null && memberUser.getBankFullName()== null) {
//                return ApiResult.error("请先完善支付信息");
//            }
            // 商品信息
            MallTimeGoods timeGoods = mallTimeGoodsService.selectMallTimeGoodsById(Long.valueOf(params.get("goodsId").toString()));
            if (memberUser.getId().equals(timeGoods.getUserId())) {
                return ApiResult.error("不可抢购自己商品");
            }
            // 抢购区域信息
            MallTimeWarehouse timeWarehouse = mallTimeWarehouseService.selectMallTimeWarehouseById(timeGoods.getRegionId());
            // 当前时分
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateNow = sd.format(new Date());
            // 截取当前时间时分
            int dateNowH = Integer.parseInt(dateNow.substring(11, 13));
            int dateNowM = Integer.parseInt(dateNow.substring(14, 16));
            // 截取开始时间时分
            int dateStartH = Integer.parseInt(timeWarehouse.getStartTime().substring(0, 2));
            int dateStartM = Integer.parseInt(timeWarehouse.getStartTime().substring(3, 5));
            // 截取结束时间时分
            int dateEndH = Integer.parseInt(timeWarehouse.getEndTime().substring(0, 2));
            int dateEndM = Integer.parseInt(timeWarehouse.getEndTime().substring(3, 5));

            int isAdvance = 0;// 是否提前进入
            if (memberUser.getIsBlock() == 1) {
                return ApiResult.error("用户状态异常");// 拉黑
            } else if (timeWarehouse.getIsOpen()== 0) {
                return ApiResult.error("该区域未开放");// 不开放
            } else if (timeGoods.getIsPublish() != 1) {
                return ApiResult.error("已售罄");// 已抢完
            } else if (memberUser.getIsBlock() == 0) {
                int isEnter = 0;
                if (!memberUser.getRegionId().equals("0")) {
                    String[] splitRegionId= memberUser.getRegionId().split(",");// 用户可进区域
                    for (String regionId : splitRegionId) {
                        if (regionId.equals(timeWarehouse.getId().toString())) {
                            isEnter = 1;
                            break;
                        }
                    }
                } else {
                    isEnter = 1;
                }
                if (isEnter == 0) {
                    return ApiResult.error("用户不可进入");
                } else if (memberUser.getExpires() != null && memberUser.getMinute() != 0) {
                    if (memberUser.getExpires().getTime() >= new Date().getTime()) {
                        if (memberUser.getMinute() > dateStartM) {
                            int hour = 60 % memberUser.getMinute();
                            if (hour == 0) {
                                dateStartH = dateStartH - 1;
                                dateStartM = 60 - memberUser.getMinute();
                            } else {
                                int minute = 60 / memberUser.getMinute();
                                dateStartH = dateStartH - hour;
                                dateStartM = 60 - minute;
                            }
                        } else {
                            dateStartM = dateStartM - memberUser.getMinute();
                        }
                        isAdvance = 1;// 提前进入
                    }
                }
            }

            // 用户今日抢购单数量
            List<MallTimeConfig> timeConfigs = mallTimeConfigService.selectMallTimeConfigList(new MallTimeConfig());
            int orderNumToday= mallTimeOrderService.timeOrderNumTodayByUserId(Long.valueOf(params.get("userId").toString()));
            if (orderNumToday > 0) {
                // 正常进入
                if (isAdvance == 0) {
                    // 今日抢购单数量大于等于设置
                    if (timeConfigs.get(0).getDayMaxBuyProduct() != 0 && orderNumToday >= timeConfigs.get(0).getDayMaxBuyProduct()) {
                        return ApiResult.error("今日已达限制次数");
                    }
                }
                // 提前进入
                if (isAdvance == 1) {
                    // 今日抢购单数量大于等于设置
                    if (timeConfigs.get(0).getAdvanceDayMaxBuyProduct() != 0 && orderNumToday >= timeConfigs.get(0).getAdvanceDayMaxBuyProduct()) {
                        return ApiResult.error("今日已达限制次数");
                    }
                }
            }

/*            int isData = 0;// 0-不能进 1-能进
            // 当前小时数在开始和结束小时数之间
            if (dateNowH >= dateStartH && dateNowH <= dateEndH) {
                // 当前小时数大于开始小时数，当前小时数小于结束小时数
                if (dateNowH > dateStartH && dateNowH < dateEndH) {
                    isData = 1;
                }
                // 当前小时数等于开始小时数
                if (dateNowH == dateStartH) {
                    // 当前分钟数大于等于开始分钟数，当前分钟数小于等于结束分钟数
                    if (dateNowM >= dateStartM && dateNowM <= dateEndM) {
                        isData = 1;
                    }
                }
                // 当前小时数等于结束小时数
                if (dateNowH == dateEndH) {
                    // 当前分钟数小于等于结束分钟数
                    if (dateNowM <= dateEndM) {
                        isData = 1;
                    }
                }
            }*/

/*            if (isData == 0) {
                return ApiResult.error("未到时间");
            } else {*/
                MallTimeOrder mallTimeOrder = new MallTimeOrder();
                mallTimeOrder.setUserId(Long.valueOf(params.get("userId").toString()));
                mallTimeOrder.setUserName(memberUser.getName());
                mallTimeOrder.setRegionId(timeGoods.getRegionId());
                mallTimeOrder.setRegionName(timeGoods.getRegionName());
                mallTimeOrder.setGoodsId(timeGoods.getId());
                mallTimeOrder.setGoodsImg(timeGoods.getCoverImg());
                mallTimeOrder.setGoodsName(timeGoods.getName());
                mallTimeOrder.setGoodsPrice(timeGoods.getPrice());
                mallTimeOrder.setOrderNumber("ZH"+generatID.getTimeRand());
                mallTimeOrder.setGoodsPrice(timeGoods.getPrice());
                mallTimeOrder.setSellerUserId(timeGoods.getUserId());
                mallTimeOrder.setSellerUserInfo(timeGoods.getUserName());
                mallTimeOrder.setBuyersUserId(memberUser.getId());
                mallTimeOrder.setBuyersUserName(memberUser.getName()+""+memberUser.getPhone());
                mallTimeOrder.setStatus(1);
                mallTimeOrder.setSellerStatus(1);
                mallTimeOrder.setPayMoney(timeGoods.getPrice());
                mallTimeOrder.setTotalPrice(timeGoods.getPrice());
                mallTimeOrder.setPayWay(1);

                mallTimeOrder.setLinkman(memberAddress.getName());
                mallTimeOrder.setMobilePhone(memberAddress.getPhone());
                mallTimeOrder.setProvince(memberAddress.getProvince());
                mallTimeOrder.setCity(memberAddress.getCity());
                mallTimeOrder.setArea(memberAddress.getArea());
                mallTimeOrder.setAddress(memberAddress.getAddress());
                mallTimeOrderService.insertMallTimeOrder(mallTimeOrder);
                // 改变商品状态
                MallTimeGoods goods = new MallTimeGoods();
                goods.setId(timeGoods.getId());
                goods.setIsPublish(2);
                mallTimeGoodsService.updateMallTimeGoods(goods);
                return ApiResult.ok("抢购成功");
//            }
        }catch (Exception e){
            return ApiResult.error("抢购失败");
        }
    }

    /**
     * 获取用户信息（支付信息等）
     *
     * userId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getUserPaymentInfo")
    public ApiResult getUserPaymentInfo(Long userId) {
        try{
            // 用户信息
            MallMemberUser user = mallMemberUserService.selectMallMemberUserById(userId);
            HashMap<String, Object> map = new HashMap<>();
            map.put("data", user);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 上传银行卡信息
     *
     * @param params
     *      userId：用户ID
     *      bankFullName：银行绑定姓名
     *      bankPhone：银行绑定手机号
     *      bankNumber：银行卡号
     *      bankName：银行开户行
     *
     * @return R.ok();
     */
    @PostMapping("/uploadBankCardInfo")
    public ApiResult uploadBankCardInfo(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("bankFullName")||StringUtils.isEmpty(params.get("bankFullName").toString())){
            return ApiResult.error("缺少银行绑定姓名");
        }
        if (!params.containsKey("bankPhone")||StringUtils.isEmpty(params.get("bankPhone").toString())){
            return ApiResult.error("缺少银行绑定手机号");
        }
        if (!params.containsKey("bankNumber")||StringUtils.isEmpty(params.get("bankNumber").toString())){
            return ApiResult.error("缺少银行卡号");
        }
        if (!params.containsKey("bankName")||StringUtils.isEmpty(params.get("bankName").toString())){
            return ApiResult.error("缺少银行开户行");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO != null) {
                userDO.setBankFullName(params.get("bankFullName").toString());
                userDO.setBankPhone(params.get("bankPhone").toString());
                userDO.setBankNumber(params.get("bankNumber").toString());
                userDO.setBankName(params.get("bankName").toString());
                mallMemberUserService.updateMallMemberUser(userDO);
            }
            return ApiResult.ok("上传成功");
        }catch (Exception e){
            return ApiResult.error("上传失败");
        }
    }

    /**
     * 上传支付宝收款码
     *
     * @param params
     *      userId：用户ID
     *      alipayCode：支付宝收款码
     *
     * @return R.ok();
     */
    @PostMapping("/uploadAlipayCode")
    public ApiResult uploadAlipayCode(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("alipayCode")||StringUtils.isEmpty(params.get("alipayCode").toString())){
            return ApiResult.error("缺少支付宝收款码");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO != null) {
                if (userDO.getAlipayCode() == null || userDO.getAlipayCode().equals("")) {
                    userDO.setAlipayCode(params.get("alipayCode").toString());
                    mallMemberUserService.updateMallMemberUser(userDO);
                } else {
                    return ApiResult.error("您已上传过支付宝收款码");
                }
            }
            return ApiResult.ok("上传成功");
        }catch (Exception e){
            return ApiResult.error("上传失败");
        }
    }

    /**
     * 上传微信收款码
     *
     * @param params
     *      userId：用户ID
     *      wxCode：微信收款码
     *
     * @return R.ok();
     */
    @PostMapping("/uploadWxCode")
    public ApiResult uploadWxCode(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("wxCode")||StringUtils.isEmpty(params.get("wxCode").toString())){
            return ApiResult.error("缺少微信收款码");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO != null) {
                if (userDO.getWxCode() == null || userDO.getWxCode().equals("")) {
                    userDO.setWxCode(params.get("wxCode").toString());
                    mallMemberUserService.updateMallMemberUser(userDO);
                } else {
                    return ApiResult.error("您已上传过微信收款码");
                }
            }
            return ApiResult.ok("上传成功");
        }catch (Exception e){
            return ApiResult.error("上传失败");
        }
    }

    /**
     * 我的仓库、买方仓库
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param userId：用户ID
     * @param type：0-我的仓库 1-买房仓库
     * @param status：我的仓库状态：1-待付款 2-付款待确认 3-待委托 4-待发货 5-待收货 6-已完成 7-已取消 8-已上架 9-已删除
     * @param sellerStatus：买方仓库状态：1-待付款 2-付款待确认 3-付款已确认 4-待发货 5-待收货 6-已完成 7-已取消 8-已上架 9-已删除
     *
     * @return R.ok();
     */
    @GetMapping("/sellerBuyerWarehouse")
    public ApiResult sellerBuyerWarehouse(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                          @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                          Long userId, Integer type, Integer status, Integer sellerStatus) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        if (type == null) {
            return ApiResult.error("缺少仓库");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            MallTimeOrder timeOrder = new MallTimeOrder();
            if (type == 0) {
                timeOrder.setUserId(userId);
                timeOrder.setStatus(status);
            } else {
                timeOrder.setSellerUserId(userId);
                timeOrder.setSellerStatus(sellerStatus);
            }
            PageHelper.startPage(pageNum,pageSize);
            List<MallTimeOrder> timeOrderList = mallTimeOrderService.selectMallTimeOrderList(timeOrder);
            PageInfo<MallTimeOrder> pageInfo = new PageInfo<>(timeOrderList);
            HashMap<String, Object> map = new HashMap<>();
            map.put("data", pageInfo);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 我的仓库商品列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param userId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getMyWarehouseGoodsList")
    public ApiResult getMyWarehouseGoodsList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                             @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                             Long userId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            MallTimeGoods timeGoods = new MallTimeGoods();
            timeGoods.setUserId(userId);
            PageHelper.startPage(pageNum,pageSize);
            List<MallTimeGoods> goodsList = mallTimeGoodsService.selectMallTimeGoodsList(timeGoods);
            PageInfo<MallTimeGoods> pageInfo = new PageInfo<>(goodsList);
            HashMap<String, Object> map = new HashMap<>();
            map.put("data", pageInfo);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 上下架商品
     *
     * @param userId：用户ID
     * @param goodsId：商品ID
     *
     * @return R.ok();
     */
    @GetMapping("/uploadTimeGoodsStatus")
    public ApiResult uploadTimeGoodsStatus(Long userId, Long goodsId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        if (goodsId == null) {
            return ApiResult.error("缺少商品ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            MallTimeGoods timeGoods = mallTimeGoodsService.selectMallTimeGoodsById(goodsId);
            if (timeGoods == null) {
                return ApiResult.error("商品错误");
            }
            if (!userId.equals(timeGoods.getUserId())) {
                return ApiResult.error("商品归属人错误");
            }
            if (timeGoods.getIsPublish() != 0 && timeGoods.getIsPublish() != 1) {
                return ApiResult.error("商品状态错误");
            }
            MallTimeGoods mallTimeGoods = new MallTimeGoods();
            mallTimeGoods.setId(goodsId);
            if (timeGoods.getIsPublish() == 0) {
                mallTimeGoods.setIsPublish(1);
            }
            if (timeGoods.getIsPublish() == 1) {
                mallTimeGoods.setIsPublish(0);
            }
            mallTimeGoodsService.updateMallTimeGoods(mallTimeGoods);
            return ApiResult.ok("修改成功");
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 取消订单
     *
     * @param userId：用户ID
     * @param orderId：订单ID
     *
     * @return R.ok();
     */
    @GetMapping("/cancelOrder")
    public ApiResult cancelOrder(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                          @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                          Long userId, Long orderId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        if (orderId == null) {
            return ApiResult.error("缺少订单ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            int order = mallTimeOrderService.cancelOrderByUserIdOrderId(userId, orderId);
            return order > 0 ? ApiResult.ok("取消成功") : ApiResult.error("取消失败");
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 买房仓库查看支付信息
     *
     * @param userId：用户ID
     * @param orderId：订单ID
     *
     * @return R.ok();
     */
    @GetMapping("/checkPaymentInfo")
    public ApiResult checkPaymentInfo(Long userId, Long orderId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        if (orderId == null) {
            return ApiResult.error("缺少订单ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            HashMap<String, Object> map = new HashMap<>();
            MallTimeOrder timeOrder = mallTimeOrderService.selectMallTimeOrderById(orderId);
            if (timeOrder != null) {
                MallTimeGoods timeGoods = mallTimeGoodsService.selectMallTimeGoodsById(timeOrder.getGoodsId());
                if (timeGoods != null) {
                    // 卖方信息
                    MallMemberUser sellerInfo = mallMemberUserService.selectMallMemberUserById(timeGoods.getUserId());
                    map.put("data", sellerInfo);
                } else {
                    return ApiResult.error("订单异常");
                }
            } else {
                return ApiResult.error("商品异常");
            }
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 上传支付凭证
     *
     * @param params
     *      userId：用户ID
     *      orderId：订单ID
     *      upPayImg：支付凭证
     *      payWay：支付方式：1-支付宝支付 2-支付宝二维码 3-微信二维码 4-银行卡 5-委托订单
     *
     * @return R.ok();
     */
    @PostMapping("/uploadPaymentVoucher")
    public ApiResult uploadPaymentVoucher(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("orderId")||StringUtils.isEmpty(params.get("orderId").toString())){
            return ApiResult.error("缺少订单ID");
        }
        if (!params.containsKey("upPayImg")||StringUtils.isEmpty(params.get("upPayImg").toString())){
            return ApiResult.error("缺少支付凭证");
        }
        if (!params.containsKey("payWay")||StringUtils.isEmpty(params.get("payWay").toString())){
            return ApiResult.error("缺少支付方式");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO != null) {
                MallTimeOrder timeOrder = new MallTimeOrder();
                timeOrder.setId(Long.valueOf(params.get("orderId").toString()));
                timeOrder.setUpPayImg(params.get("upPayImg").toString());
                timeOrder.setPayWay(Integer.valueOf(params.get("payWay").toString()));
                timeOrder.setStatus(2);
                timeOrder.setSellerStatus(2);
                timeOrder.setPayTime(new Date());
                timeOrder.setSellerReviewTime(new Date());
                mallTimeOrderService.updateMallTimeOrder(timeOrder);
            }
            return ApiResult.ok("上传成功");
        }catch (Exception e){
            return ApiResult.error("上传失败");
        }
    }

    /**
     * 卖方仓库查看买方信息
     *
     * @param userId：用户ID
     * @param orderId：订单ID
     *
     * @return R.ok();
     */
    @GetMapping("/checkBuyerInfo")
    public ApiResult checkBuyerInfo(Long userId, Long orderId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        if (orderId == null) {
            return ApiResult.error("缺少订单ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            HashMap<String, Object> map = new HashMap<>();
            MallTimeOrder timeOrder = mallTimeOrderService.selectMallTimeOrderById(orderId);
            if (timeOrder != null) {
                // 买方信息
                MallMemberUser buyerInfo = mallMemberUserService.selectMallMemberUserById(timeOrder.getUserId());
                if (buyerInfo != null) {
                    map.put("data", buyerInfo);
                } else {
                    return ApiResult.error("买方信息异常");
                }
            } else {
                return ApiResult.error("订单异常");
            }
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 卖方确认已付款
     *
     * @param params
     *      userId：用户ID
     *      orderId：订单ID
     *
     * @return R.ok();
     */
    @PostMapping("/confirmThePayment")
    public ApiResult confirmThePayment(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("orderId")||StringUtils.isEmpty(params.get("orderId").toString())){
            return ApiResult.error("缺少订单ID");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO == null) {
                return ApiResult.error("用户信息异常");
            }
            int confirmThePayment = mallTimeOrderService.confirmThePayment(Long.valueOf(params.get("userId").toString()), Long.valueOf(params.get("orderId").toString()));
            return confirmThePayment > 0 ? ApiResult.ok("已确认付款") : ApiResult.error("确认付款失败");
        }catch (Exception e){
            return ApiResult.error("确认付款失败");
        }
    }

    /**
     * 商品委托信息
     *
     * @param userId：用户ID
     * @param orderId：订单ID
     * @param couponId：优惠券ID
     *
     * @return R.ok();
     */
    @GetMapping("/getGoodsEntrustInfo")
    public ApiResult getGoodsEntrustInfo(Long userId, Long orderId, Long couponId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        if (orderId == null) {
            return ApiResult.error("缺少订单ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            HashMap<String, Object> map = new HashMap<>();
            MallTimeOrder timeOrder = mallTimeOrderService.selectMallTimeOrderById(orderId);
            if (timeOrder != null) {
                // 商品委托信息
                MallTimeGoods timeGoods = mallTimeGoodsService.selectMallTimeGoodsById(timeOrder.getGoodsId());
                if (timeGoods != null) {
                    // 基础设置
                    MallTimeConfig timeConfig = mallTimeConfigService.findMallTimeConfig();
                    timeGoods.setOrderNumber(timeOrder.getOrderNumber());
                    // 委托商品价=商品价+商品价*委托商品价比例（四舍五入取整）
                    if (timeConfig.getProductEntrustScale().equals(new BigDecimal(0))) {
                        timeGoods.setActualUpFee(timeGoods.getPrice());
                    } else {
                        timeGoods.setActualUpFee(timeGoods.getPrice().multiply(timeConfig.getProductEntrustScale()).multiply(new BigDecimal("0.01")).add(timeGoods.getPrice()).setScale(0, RoundingMode.HALF_UP));
                    }
                    // 手续费=商品价*委托费比例（四舍五入取整）
                    BigDecimal upFee = new BigDecimal(0);
                    if (!timeConfig.getEntrustScale().equals(new BigDecimal(0))) {
                        upFee =  timeGoods.getPrice().multiply(timeConfig.getEntrustScale()).multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP);
                    }
                    timeGoods.setUpFee(upFee);
                    // 实付手续费
                    if (couponId != null) {
                        MallMemberCoupon coupon = mallMemberCouponService.selectMallMemberCouponById(couponId);
                        if (coupon != null) {
                            timeGoods.setRealUpFee(upFee.subtract(coupon.getPrice()));
                        } else {
                            timeGoods.setRealUpFee(upFee);
                        }
                    } else {
                        timeGoods.setRealUpFee(upFee);
                    }
                    map.put("data", timeGoods);
                }
            } else {
                return ApiResult.error("订单异常");
            }
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 查看优惠券列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param userId：用户ID
     * @param orderId：订单ID
     *
     * @return R.ok();
     */
    @GetMapping("/viewCoupons")
    public ApiResult viewCoupons(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                 @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                 Long userId, Long orderId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        if (orderId == null) {
            return ApiResult.error("缺少订单ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            HashMap<String, Object> map = new HashMap<>();
            MallTimeOrder timeOrder = mallTimeOrderService.selectMallTimeOrderById(orderId);
            if (timeOrder != null) {
                // 商品委托信息
                MallTimeGoods timeGoods = mallTimeGoodsService.selectMallTimeGoodsById(timeOrder.getGoodsId());
                if (timeGoods != null) {
                    // 基础设置
                    MallTimeConfig timeConfig = mallTimeConfigService.findMallTimeConfig();
                    timeGoods.setOrderNumber(timeOrder.getOrderNumber());
                    // 手续费=商品价*委托费比例（四舍五入取整）
                    BigDecimal upFee = new BigDecimal(0);
                    if (!timeConfig.getEntrustScale().equals(new BigDecimal(0))) {
                        upFee = timeGoods.getPrice().multiply(timeConfig.getEntrustScale()).multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP);
                    }
                    PageHelper.startPage(pageNum,pageSize);
                    List<MallMemberCoupon> memberCouponList = mallMemberCouponService.selectCanMemberCouponList(userId, upFee);
                    PageInfo<MallMemberCoupon> pageInfo = new PageInfo<>(memberCouponList);
                    map.put("data", pageInfo);
                }
            } else {
                return ApiResult.error("订单异常");
            }
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 委托上架
     *
     * @param params
     *      userId：用户ID
     *      orderId：订单ID
     *      couponId：优惠券ID
     *      upFee：手续费
     *      realUpFee：实付手续费
     *      entrustPrice：委托价
     *
     * @return R.ok();
     */
    @PostMapping("/entrustGrounding")
    public ApiResult entrustGrounding(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("orderId")||StringUtils.isEmpty(params.get("orderId").toString())){
            return ApiResult.error("缺少订单ID");
        }
        if (!params.containsKey("upFee")||StringUtils.isEmpty(params.get("upFee").toString())){
            return ApiResult.error("缺少手续费");
        }
        if (!params.containsKey("realUpFee")||StringUtils.isEmpty(params.get("realUpFee").toString())){
            return ApiResult.error("缺少实付手续费");
        }
        if (!params.containsKey("entrustPrice")||StringUtils.isEmpty(params.get("entrustPrice").toString())){
            return ApiResult.error("缺少委托价");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO == null) {
                return ApiResult.error("用户信息异常");
            }
            // 订单信息
            MallTimeOrder timeOrder = mallTimeOrderService.selectMallTimeOrderById(Long.valueOf(params.get("orderId").toString()));
            if (timeOrder == null) {
                return ApiResult.error("订单信息异常");
            }
            if (timeOrder.getStatus() != 3) {
                return ApiResult.error("订单状态异常");
            }
            // 商品信息
            MallTimeGoods timeGoods = mallTimeGoodsService.selectMallTimeGoodsById(timeOrder.getGoodsId());
            if (timeGoods == null) {
                return ApiResult.error("商品异常");
            }
            // 支付信息
            if (userDO.getBankFullName()==null && userDO.getWxCode()==null && userDO.getAlipayCode()==null) {
                return ApiResult.error("请先完善支付信息");
            }
            // 手续费
            BigDecimal proceduresPrice = new BigDecimal(params.get("upFee").toString());
            // 实付手续费
            BigDecimal realUpFee = new BigDecimal(params.get("realUpFee").toString());
            // 委托价
            BigDecimal entrustPrice = new BigDecimal(params.get("entrustPrice").toString());
            // 抢购区域信息
            MallTimeWarehouse timeWarehouse = mallTimeWarehouseService.selectMallTimeWarehouseById(timeOrder.getRegionId());
            // 当前时分
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateNow = sd.format(new Date());
            // 截取当前时间时分
            int dateNowH = Integer.parseInt(dateNow.substring(11, 13));
            int dateNowM = Integer.parseInt(dateNow.substring(14, 16));
            // 截取开始时间时分
            int dateStartH = Integer.parseInt(timeWarehouse.getStartTime().substring(0, 2));
            int dateStartM = Integer.parseInt(timeWarehouse.getStartTime().substring(3, 5));
            // 截取结束时间时分
            int dateEndH = Integer.parseInt(timeWarehouse.getEndTime().substring(0, 2));
            int dateEndM = Integer.parseInt(timeWarehouse.getEndTime().substring(3, 5));
            // 活动开始前时分
            int actBeforeH = Integer.parseInt(timeWarehouse.getStartTime().substring(0, 2)) - timeWarehouse.getBeforeTime();
            int actBeforeM = Integer.parseInt(timeWarehouse.getStartTime().substring(3, 5));
            // 活动结束后时分
            int actAfterH = Integer.parseInt(timeWarehouse.getEndTime().substring(0, 2)) + timeWarehouse.getAfterTime();
            int actAfterM = Integer.parseInt(timeWarehouse.getEndTime().substring(3, 5));

            int isGrounding = 1;// 0-不能委托上架 1-能委托上架
            // 活动开始前1小时、结束后1小时内不能上架
            // 当前小时在活动开始前与开始之间
            if (dateNowH >= actBeforeH && dateNowH <= dateStartH) {
                //
                if (dateNowH == actBeforeH) {
                    // 当前分钟大于等于活动开始前
                    if (dateNowM >= actBeforeM) {
                        isGrounding = 0;
                    }
                }
                if (dateNowH == dateStartH) {
                    // 当前分钟小于等于活动开始前
                    if (dateNowM <= dateStartM) {
                        isGrounding = 0;
                    }
                }
            }
            // 当前小时在结束与活动结束后之间
            if (dateNowH >= dateEndH && dateNowH <= actAfterH) {
                //
                if (dateNowH == dateEndH) {
                    // 当前分钟大于等于活动开始前
                    if (dateNowM >= dateEndM) {
                        isGrounding = 0;
                    }
                }
                if (dateNowH == actAfterH) {
                    // 当前分钟小于等于活动开始前
                    if (dateNowM <= actAfterM) {
                        isGrounding = 0;
                    }
                }
            }
            if (isGrounding == 0) {
                return ApiResult.error("不在委托上架时间");
            } else {
                // 改订单
                MallTimeOrder mallTimeOrder = new MallTimeOrder();
                mallTimeOrder.setId(Long.valueOf(params.get("orderId").toString()));
                mallTimeOrder.setStatus(8);
                mallTimeOrder.setEntrustPrice(entrustPrice);
                mallTimeOrder.setProceduresPrice(proceduresPrice);
                mallTimeOrder.setEntrustDiscountPrice(proceduresPrice.divide(realUpFee));
                mallTimeOrderService.updateMallTimeOrder(mallTimeOrder);
                // 改商品
                MallTimeGoods mallTimeGoods = new MallTimeGoods();
                mallTimeGoods.setId(timeGoods.getId());
                mallTimeGoods.setPrice(entrustPrice);
                mallTimeGoods.setUpFee(entrustPrice);
                mallTimeGoods.setIsPublish(1);
                mallTimeGoods.setIsPay(0);
                mallTimeGoodsService.updateMallTimeGoods(mallTimeGoods);
            }
            return ApiResult.ok();
        }catch (Exception e){
            return ApiResult.error("确认付款失败");
        }
    }

    /**
     * 发货
     *
     * @param params
     *      userId：用户ID
     *      orderId：订单ID
     *
     * @return R.ok();
     */
    @PostMapping("/sendOutGoods")
    public ApiResult sendOutGoods(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("orderId")||StringUtils.isEmpty(params.get("orderId").toString())){
            return ApiResult.error("缺少订单ID");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO == null) {
                return ApiResult.error("用户信息异常");
            }
            MallTimeOrder timeOrder = mallTimeOrderService.selectMallTimeOrderById(Long.valueOf(params.get("orderId").toString()));
            if (timeOrder == null) {
                return ApiResult.error("订单信息异常");
            }
            if (timeOrder.getStatus() != 3) {
                return ApiResult.error("订单状态错误");
            }
            MallTimeGoods timeGoods = mallTimeGoodsService.selectMallTimeGoodsById(timeOrder.getGoodsId());
            if (timeGoods == null) {
                return ApiResult.error("商品错误");
            }
            if (timeGoods.getIsPublish() != 0) {
                return ApiResult.error("请先下架商品，再发货");
            }
            MallTimeOrder order = new MallTimeOrder();
            order.setId(timeOrder.getId());
            order.setStatus(4);
            mallTimeOrderService.updateMallTimeOrder(order);
            // 改商品状态
            MallTimeGoods goods = new MallTimeGoods();
            goods.setId(timeOrder.getGoodsId());
            goods.setIsPublish(3);
            mallTimeGoodsService.updateMallTimeGoods(goods);
            return ApiResult.ok("提交成功");
        }catch (Exception e){
            return ApiResult.error("提交失败");
        }
    }

    /**
     * 确认收货
     *
     * @param params
     *      userId：用户ID
     *      orderId：订单ID
     *
     * @return R.ok();
     */
    @PostMapping("/confirmReceipt")
    public ApiResult confirmReceipt(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("orderId")||StringUtils.isEmpty(params.get("orderId").toString())){
            return ApiResult.error("缺少订单ID");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO == null) {
                return ApiResult.error("用户信息异常");
            }
            ApiResult apiResult = mallTimeOrderService.confirmReceipt(Long.valueOf(params.get("userId").toString()), Long.valueOf(params.get("orderId").toString()));
            return apiResult;
        }catch (Exception e){
            return ApiResult.error("确认付款失败");
        }
    }

    /**
     * 绑定推荐人
     *
     * @param params
     *      userId：用户ID
     *      phone：推荐人手机号
     *
     * @return R.ok();
     */
    @PostMapping("/bindingReferee")
    public ApiResult bindingReferee(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("phone")||StringUtils.isEmpty(params.get("phone").toString())){
            return ApiResult.error("缺少推荐人");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO == null) {
                return ApiResult.error("用户信息异常");
            }
            if (userDO.getIntroUser() != 0) {
                return ApiResult.error("您已绑定");
            }
            // 推荐人信息
            MallMemberUser userByPhone = mallMemberUserService.selectMallMemberUserByPhone(params.get("phone").toString());
            if (userByPhone == null) {
                return ApiResult.error("推荐人不存在");
            }
            if (userByPhone.getId().equals(Long.valueOf(params.get("userId").toString()))) {
                return ApiResult.error("不可绑定自己");
            }
            userDO.setIntroUser(userByPhone.getId());
            userDO.setIntroUserInfo(userByPhone.getName()+"--"+userByPhone.getPhone());
            int user = mallMemberUserService.updateMallMemberUser(userDO);
            return user > 0 ? ApiResult.ok("绑定成功") : ApiResult.error("绑定失败");
        }catch (Exception e){
            return ApiResult.error("确认付款失败");
        }
    }

    /**
     * 获取我的余额
     *
     * @param userId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getMyBalance")
    public ApiResult getMyBalance(Long userId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(userId);
            if (userDO == null) {
                return ApiResult.error("用户信息异常");
            }
            // 我的返佣金额
            BigDecimal rakeBackByUserId = mallTimeWithdrawService.selectTimeWithdrawRakeBackByUserId(userId);
            // 我的提现金额
            BigDecimal cashOutByUserId = mallTimeWithdrawService.selectTimeWithdrawCashOutByUserId(userId);
            // 今日获得
            BigDecimal todayGainByUserId = mallTimeWithdrawService.selectTimeWithdrawTodayGainByUserId(userId);
            // 近七日获得
            BigDecimal sevenDaysGainByUserId = mallTimeWithdrawService.selectTimeWithdrawSevenDaysGainByUserId(userId);
            // 我的余额
            BigDecimal myBalance = rakeBackByUserId.subtract(cashOutByUserId);
            HashMap<String, Object> map = new HashMap<>();
            userDO.setMoney(myBalance);
            userDO.setAllGain(rakeBackByUserId);
            userDO.setTodayGain(todayGainByUserId);
            userDO.setSevenDaysGain(sevenDaysGainByUserId);
            map.put("data", userDO);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 获取分销说明
     **
     * @return R.ok();
     */
    @GetMapping("/getDistributionExplain")
    public ApiResult getDistributionExplain() {
        try {
            // 分销说明
            MallDistributionConfig config = mallDistributionConfigService.findMallDistributionConfig();
            HashMap<String, Object> map = new HashMap<>();
            map.put("data", config);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 用户提现
     *
     * @param params
     *      userId：用户ID
     *      price：提现金额
     *      withdrawType：提现方式 1-微信 2-支付宝 3-银行卡（现固定为2）
     *      aliPayAccount：支付宝账号
     *      aliPayName：支付宝姓名
     *      mobilePhone：手机号
     *
     * @return R.ok();
     */
    @PostMapping("/userCashOut")
    public ApiResult userCashOut(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("缺少用户ID");
        }
        if (!params.containsKey("price")||StringUtils.isEmpty(params.get("price").toString())){
            return ApiResult.error("缺少提现金额");
        }
        if (!params.containsKey("withdrawType")||StringUtils.isEmpty(params.get("withdrawType").toString())){
            return ApiResult.error("缺少提现方式");
        }
        if (!params.containsKey("aliPayAccount")||StringUtils.isEmpty(params.get("aliPayAccount").toString())){
            return ApiResult.error("缺少支付宝账号");
        }
        if (!params.containsKey("aliPayName")||StringUtils.isEmpty(params.get("aliPayName").toString())){
            return ApiResult.error("缺少支付宝姓名");
        }
        if (!params.containsKey("mobilePhone")||StringUtils.isEmpty(params.get("mobilePhone").toString())){
            return ApiResult.error("缺少手机号");
        }
        try {
            // 用户信息
            MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
            if (userDO == null) {
                return ApiResult.error("用户信息异常");
            }
            // 我的返佣金额
            BigDecimal rakeBackByUserId = mallTimeWithdrawService.selectTimeWithdrawRakeBackByUserId(Long.valueOf(params.get("userId").toString()));
            // 我的提现金额
            BigDecimal cashOutByUserId = mallTimeWithdrawService.selectTimeWithdrawCashOutByUserId(Long.valueOf(params.get("userId").toString()));
            // 我的余额
            BigDecimal myBalance = rakeBackByUserId.subtract(cashOutByUserId);
            // 提现金额设置
            MallDistributionConfig config = mallDistributionConfigService.findMallDistributionConfig();
            // 提现金额
            BigDecimal price = new BigDecimal(params.get("price").toString());
            // 手续费
            BigDecimal proceduresPrice = new BigDecimal(0);
            if (new BigDecimal(0).compareTo(config.getWithdrawCost()) < 0) {
                proceduresPrice = price.multiply(config.getWithdrawCost().multiply(new BigDecimal("0.01"))).setScale(2, RoundingMode.HALF_UP);
            }
            if(myBalance.compareTo(config.getFullPrice()) < 0) {
                return ApiResult.error("满"+config.getFullPrice()+"可提现");
            } else if (myBalance.compareTo(price) < 0){
                return ApiResult.error("余额不足");
            } else if (price.compareTo(config.getWithdrawMin()) < 0){
                return ApiResult.error("最小提现金额"+config.getWithdrawMin()+"元");
            }
            else {
                MallTimeWithdraw timeWithdraw = new MallTimeWithdraw();
                timeWithdraw.setWithdrawId("WD"+ generatID.getTimeRand());
                timeWithdraw.setUserId(Long.valueOf(params.get("userId").toString()));
                timeWithdraw.setUserName(userDO.getName());
                timeWithdraw.setMoney(price);
                timeWithdraw.setWithdrawCost(proceduresPrice);
                timeWithdraw.setActualMoney(price.subtract(proceduresPrice).setScale(2, RoundingMode.HALF_UP));
                timeWithdraw.setType(1);
                timeWithdraw.setWithdrawType(2);
                timeWithdraw.setAliPayAccount(params.get("aliPayAccount").toString());
                timeWithdraw.setAliPayName(params.get("aliPayName").toString());
                timeWithdraw.setMobilePhone(params.get("mobilePhone").toString());
                timeWithdraw.setStatus(1);
                timeWithdraw.setIsArrival(1);
                mallTimeWithdrawService.insertMallTimeWithdraw(timeWithdraw);
                return ApiResult.ok("提现成功，等待审核");
            }
        }catch (Exception e){
            return ApiResult.error("提现失败");
        }
    }

    /**
     * 获取我的佣金、提现记录列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param userId：用户ID
     * @param type：类型：0-返佣 1-提现
     *
     * @return R.ok();
     */
    @GetMapping("/getMyCommissionList")
    public ApiResult getMyCommissionList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                         @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                         Long userId, Integer type) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        if (type == null) {
            return ApiResult.error("缺少类型");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            HashMap<String, Object> map = new HashMap<>();
            PageHelper.startPage(pageNum,pageSize);
            List<MallTimeWithdraw> list = mallTimeWithdrawService.selectMyWithdrawList(userId, type);
            PageInfo<MallTimeWithdraw> pageInfo = new PageInfo<>(list);
            map.put("data", pageInfo);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 获取我的粉丝列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param userId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getMyFansList")
    public ApiResult getMyFansList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                   @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                   Long userId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            HashMap<String, Object> map = new HashMap<>();
            PageHelper.startPage(pageNum,pageSize);
            MallMemberUser user = new MallMemberUser();
            user.setIntroUser(userId);
            List<MallMemberUser> list = mallMemberUserService.selectMallMemberUserList(user);
            PageInfo<MallMemberUser> pageInfo = new PageInfo<>(list);
            map.put("data", pageInfo);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 获取我的粉丝订单列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param userId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getMyFansOrderList")
    public ApiResult getMyFansOrderList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                   @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                   Long userId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            HashMap<String, Object> map = new HashMap<>();
            PageHelper.startPage(pageNum,pageSize);
            List<MallTimeOrder> orderList = mallTimeOrderService.selectMyFansTimeOrderList(userId);
            PageInfo<MallTimeOrder> pageInfo = new PageInfo<>(orderList);
            map.put("data", pageInfo);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

    /**
     * 测试
     *
     * @return R.ok();
     */
    @GetMapping("/test")
    public ApiResult test(BigDecimal money) {
        try{
            HashMap<String, Object> map = new HashMap<>();
            /*UUID uuid1 = UUID.randomUUID();
            String uuid2 = UUID.randomUUID().toString().replace("-","");
            String uuid3 = generatID.getTimeRand();
            String uuid4 = generatID.getDate();
            String uuid5 = generatID.getTimeStamp();
            String uuid6 = IdUtils.simpleUUID();
            map.put("uuid1:", uuid1);
            map.put("uuid2:", uuid2);
            map.put("uuid3:", uuid3);
            map.put("uuid4:", uuid4);
            map.put("uuid5:", uuid5);
            map.put("uuid6:", uuid6);*/
//            MallMemberUser mallMemberUser = mallMemberUserService.selectMallMemberUserById(11L);
            BigDecimal decimal = new BigDecimal(String.valueOf(money));
            BigDecimal upFee =  decimal.multiply(new BigDecimal("2")).multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP);
            map.put("upFee:", upFee);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }


    /**
     * 支付委托手续费
     * @param userId：用户ID
     * @param orderId：订单ID
     * @param realUpFee：实付手续费
     * @param entrustPrice：委托价
     * @param upFee：手续费
     * @param couponId：优惠券ID
     * @param req
     * @return
     */
    @GetMapping("/entrustFeePay")
    public ApiResult entrustFeePay(@RequestParam Long userId, Long orderId, Long couponId, BigDecimal realUpFee, BigDecimal entrustPrice, BigDecimal upFee, HttpServletRequest req){
        // 用户信息
        MallMemberUser userDO = mallMemberUserService.selectMallMemberUserById(userId);
        if (userDO == null) {
            return ApiResult.error("用户信息异常");
        }
        // 订单信息
        MallTimeOrder timeOrder = mallTimeOrderService.selectMallTimeOrderById(orderId);
        if (timeOrder == null) {
            return ApiResult.error("订单信息异常");
        }
        if (timeOrder.getStatus() != 3) {
            return ApiResult.error("订单状态异常");
        }
        // 商品信息
        MallTimeGoods timeGoods = mallTimeGoodsService.selectMallTimeGoodsById(timeOrder.getGoodsId());
        if (timeGoods == null) {
            return ApiResult.error("商品异常");
        }
        // 优惠券信息
        if (couponId != null) {
            MallMemberCoupon memberCoupon = mallMemberCouponService.selectMallMemberCouponById(couponId);
            if (memberCoupon == null || memberCoupon.getIsUsed().equals("1")) {
                return ApiResult.error("优惠券状态异常");
            }
        }
        // 用户支付信息
        if (userDO.getBankFullName() == null && userDO.getWxCode() == null && userDO.getAlipayCode() == null) {
            return ApiResult.error("请先完善支付信息");
        }
        // 抢购区域信息
        MallTimeWarehouse timeWarehouse = mallTimeWarehouseService.selectMallTimeWarehouseById(timeOrder.getRegionId());
        // 当前时分
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNow = sd.format(new Date());
        // 截取当前时间时分
        int dateNowH = Integer.parseInt(dateNow.substring(11, 13));
        int dateNowM = Integer.parseInt(dateNow.substring(14, 16));
        // 活动开始前时分
        int actBeforeH = Integer.parseInt(timeWarehouse.getStartTime().substring(0, 2)) - timeWarehouse.getBeforeTime();
        int actBeforeM = Integer.parseInt(timeWarehouse.getStartTime().substring(3, 5));
        // 活动结束后时分
        int actAfterH = Integer.parseInt(timeWarehouse.getEndTime().substring(0, 2)) + timeWarehouse.getAfterTime();
        int actAfterM = Integer.parseInt(timeWarehouse.getEndTime().substring(3, 5));

        int isGrounding = 1;// 0-不能委托上架 1-能委托上架
        // 活动开始前1小时到结束后1小时内不能上架
        // 当前小时在活动开始前与活动结束后之间
        if (dateNowH >= actBeforeH && dateNowH <= actAfterH) {
            // 当前小时大于活动开始前、小于活动结束后
            if (dateNowH > actBeforeH && dateNowH < actAfterH) {
                isGrounding = 0;
            }
            // 当前小时等于活动开始前 当前分钟大于等于活动开始前
            if (dateNowH == actBeforeH && dateNowM >= actBeforeM) {
                isGrounding = 0;
            }
            // 当前小时等于活动结束后 当前分钟小于等于活动开始前
            if (dateNowH == actAfterH && dateNowM <= actAfterM) {
                isGrounding = 0;
            }
        }
        if (isGrounding == 0) {
            return ApiResult.error("不在委托上架时间");
        }

        HashMap<String, Object> map = new HashMap<>();
        //时间戳
        map.put("timeStamp", DateUtils.getNowDate().getTime()+"");

        //调用统一下单接口拿到prepay_id
        SortedMap<String, Object> date = new TreeMap<String,Object>();

        //返回用前端的date2
        SortedMap<String, Object> date2 = new TreeMap<String,Object>();
        date2.put("appId", "wxb2bacd262ba9746b");
        date2.put("timeStamp",DateUtils.getNowDate().getTime());
        date2.put("signType","MD5");

        date.put("appid","wxb2bacd262ba9746b");
        date.put("attach","五寸方委托手续费支付");
        date.put("openid",userDO.getOpenid());
        date.put("body","五寸方委托手续费支付");
        date.put("mch_id","1622749132");
        date.put("nonce_str",generatID.getTimeRand());
        date.put("notify_url","https://xcx.shijinjiapei.com/v4/web/xuansTea/api/timeArea/result");
        date.put("out_trade_no",timeOrder.getId()+"-"+generatID.getTimeRand());
        date.put("spbill_create_ip", StringUtils.getRemoteAddr(req));
        float sessionmoney = Float.parseFloat(realUpFee.toString());
        String finalmoney = String.format("%.2f", sessionmoney);
        finalmoney = finalmoney.replace(".", "");
        String newStr = finalmoney.replaceFirst("^0*", "");
        date.put("total_fee",newStr);
        date.put("trade_type","JSAPI");
        String perpayId = WeixinUtils.getPerpayId(date,date2);

        date2.put("package", FBSStringUtil.format("prepay_id={0}",perpayId));

        map.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));
        //paySign 签名
        map.put("paySign",WeixinUtils.createSign(WeixinUtils.CHARSET,date2));
        //随机字符串
        map.put("nonceStr",date2.get("nonceStr"));

        //生成支付记录
        MallPayLog payLog = new MallPayLog();
        payLog.setId("PL"+ generatID.getTimeRand());
        payLog.setOutTradeNo((String) date.get("out_trade_no"));
        payLog.setStatus("0");
        payLog.setResId(timeOrder.getId());
        payLog.setType("2");// 支付类型: 0-订单支付 1-会员支付 2-委托费支付
        payLog.setUserId(userId);
        payLog.setPrice(realUpFee);
        payLog.setCreateAt(DateUtils.getTime());
        payLog.setEntrustPrice(entrustPrice);
        payLog.setProceduresPrice(upFee);
        payLog.setCouponId(couponId);
        mallPayLogService.insertMallPayLog(payLog);

        return ApiResult.ok(map);
    }

    /**
     * 微信回调方法
     * @param req
     * @param res
     * @return
     */
    @PostMapping("/result")
    public Object vipResult(HttpServletRequest req, HttpServletResponse res){
        try {
            InputStream inStream = req.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            System.out.println("~~~~~~~~~~~~~~~~合同支付成功~~~~~~~~~");
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map<Object, Object> mapFromXml = WeixinUtils.doXMLParse(result);
            SortedMap<String ,String > sortedMap = new TreeMap();
            if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
                // 支付信息
                MallPayLog payLog = mallPayLogService.selectPayLogByNo(mapFromXml.get("out_trade_no").toString());
                if(payLog.getStatus().equals("0")){

                    String orderNo = mapFromXml.get("out_trade_no").toString().split("-")[0];
                    Date date = new Date();
                    // 订单信息
                    MallTimeOrder byOrderNo = mallTimeOrderService.selectMallTimeOrderById(Long.valueOf(orderNo));
                    if (byOrderNo == null){
                        sortedMap.put("return_code","FAIL");
                        sortedMap.put("return_msg","签名失败");
                        res.reset();
                        res.getWriter().write(parseXML(sortedMap));
                    }
                    // 商品信息
                    MallTimeGoods timeGoods = mallTimeGoodsService.selectMallTimeGoodsById(byOrderNo.getGoodsId());
                    // 验签成功后
                    // 改订单
                    MallTimeOrder mallTimeOrder = new MallTimeOrder();
                    mallTimeOrder.setId(byOrderNo.getId());
                    mallTimeOrder.setStatus(8);
                    mallTimeOrder.setEntrustPrice(payLog.getEntrustPrice());
                    mallTimeOrder.setProceduresPrice(payLog.getProceduresPrice());
                    mallTimeOrder.setEntrustDiscountPrice(payLog.getProceduresPrice().divide(payLog.getPrice()));
                    mallTimeOrderService.updateMallTimeOrder(mallTimeOrder);
                    // 改商品
                    MallTimeGoods mallTimeGoods = new MallTimeGoods();
                    mallTimeGoods.setId(timeGoods.getId());
                    mallTimeGoods.setPrice(payLog.getEntrustPrice());
                    mallTimeGoods.setUpFee(payLog.getEntrustPrice());
                    mallTimeGoods.setIsPublish(1);
                    mallTimeGoods.setIsPay(0);
                    mallTimeGoodsService.updateMallTimeGoods(mallTimeGoods);
                    // 更新支付记录
                    payLog.setStatus("1");
                    mallPayLogService.updateMallPayLog(payLog);
                    // 改优惠券
                    if (payLog.getCouponId() != null) {
                        MallMemberCoupon memberCoupon = mallMemberCouponService.selectMallMemberCouponById(payLog.getCouponId());
                        memberCoupon.setIsUsed("1");
                        mallMemberCouponService.updateMallMemberCoupon(memberCoupon);
                    }
                }
                sortedMap.put("return_code","SUCCESS");
                sortedMap.put("return_msg","OK");
                BufferedOutputStream out = new BufferedOutputStream(
                        res.getOutputStream());
                out.write(parseXML(sortedMap).getBytes());
                out.flush();
                out.close();

            }else {
                sortedMap.put("return_code","FAIL");
                sortedMap.put("return_msg","签名失败");
                BufferedOutputStream out = new BufferedOutputStream(
                        res.getOutputStream());
                out.write(parseXML(sortedMap).getBytes());
                out.flush();
                out.close();
            }
            return "success";
        } catch (Exception e) {
            return "failure";
        }
    }


    //输出XML
    public String parseXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>\n");
        Set es = map.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(null != v && !"".equals(v) && !"appkey".equals(k)) {

                sb.append("<" + k +"><![CDATA[" + v + "]]></" + k + ">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 获取我的优惠券列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数据量
     * @param userId：用户ID
     *
     * @return R.ok();
     */
    @GetMapping("/getMyCouponList")
    public ApiResult getMyCouponList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                   @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                   Long userId) {
        if (userId == null) {
            return ApiResult.error("缺少用户ID");
        }
        try{
            // 用户信息
            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return ApiResult.error("用户异常");
            }
            HashMap<String, Object> map = new HashMap<>();
            PageHelper.startPage(pageNum,pageSize);
            MallMemberCoupon memberCoupon = new MallMemberCoupon();
            memberCoupon.setUserId(userId);
            memberCoupon.setIsUsed("0");
            List<MallMemberCoupon> list = mallMemberCouponService.selectMallMemberCouponList(memberCoupon);
            PageInfo<MallMemberCoupon> pageInfo = new PageInfo<>(list);
            map.put("data", pageInfo);
            return ApiResult.ok(map);
        }catch (Exception e){
            return ApiResult.error("服务器网络异常");
        }
    }

//    /**
//     * 今日数据折线图接口
//     *
//     * @param
//     * @return 单条数据
//     */
//    @GetMapping("/today/lineChart")
//    public AjaxResult todayLineChart() {
//        Map<String, Object> queryTodayLineChart = mallTimeOrderService.queryTodayLineChart();
//        Map<String,Object> map = new HashMap<>();
//        // 订单数
//        map.put("orderNum",queryTodayLineChart.get("orderNum"));
//        // 购买人数
//        map.put("buyerNum",queryTodayLineChart.get("buyerNum"));
//        // 当日流水
//        map.put("todayRunWater",queryTodayLineChart.get("todayRunWater"));
//        return AjaxResult.success(map);
//    }
//
//    /**
//     * 历史数据折线图接口
//     *
//     * @param
//     * @return 单条数据
//     */
//    @PostMapping("/history/lineChart")
//    public AjaxResult countLineChart(@RequestBody Map<String,Object> map) {
//        String beginAt = map.get("beginAt").toString();
//        String endAt = map.get("endAt").toString();
//        Date beginTime = null;
//        Date endTime = null;
//        Calendar c = Calendar.getInstance();
//        if (StringUtils.isNotEmpty(beginAt)){
//            beginAt = beginAt+" 00:00:00";
//            endAt = endAt+" 23:59:59";
//
//            beginTime = DateUtils.parseDate(beginAt);
//            endTime = DateUtils.parseDate(endAt);
//        }else {
//            c.setTime(DateUtils.getNowDate());
//            c.add(Calendar.DATE, -30);
//            String day = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,c.getTime());
//            beginAt = day+" 00:00:00";
//            endAt = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,DateUtils.getNowDate())+" 23:59:59";
//
//            beginTime = DateUtils.parseDate(beginAt);
//            endTime = DateUtils.parseDate(endAt);
//        }
//
//        List<BigDecimal> runWaterList = new ArrayList<>();
//        List<BigDecimal> turnoverList = new ArrayList<>();
//        List<BigDecimal> sharePriceList = new ArrayList<>();
//        List<Integer> dealNumList = new ArrayList<>();
//        List<Integer> buyerNumList = new ArrayList<>();
//        List<String> dayList = new ArrayList<>();
//        while (beginTime.getTime()<=endTime.getTime()){
//            String day = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,beginTime);
//            beginAt = day +" 00:00:00";
//            endAt = day + " 23:59:59";
//            dayList.add(day);
//            map.put("beginAt",beginAt);
//            map.put("endAt",endAt);
//            Map<String,Object> cm = mallTimeOrderService.queryHistoryLineChart(map);
//            runWaterList.add(new BigDecimal(cm.get("runWaterList").toString()));
//            buyerNumList.add(Integer.parseInt(cm.get("buyerNumList").toString()));
//            Map<String,Object> cm2 = mallTimeOrderService.queryHistoryLineChart2(map);
//            turnoverList.add(new BigDecimal(cm2.get("turnoverList").toString()));
//            dealNumList.add(Integer.parseInt(cm2.get("dealNumList").toString()));
//            Map<String, Object> cm3 = mallTimeWithdrawService.queryHistoryLineChartSharePrice(map);
//            sharePriceList.add(new BigDecimal(cm3.get("sharePriceList").toString()));
//            c.setTime(beginTime);
//            c.add(Calendar.DATE, 1);
//            beginTime = c.getTime();
//        }
//        Map<String,Object> rm = new HashMap<>();
//        // 流水
//        rm.put("runWaterList",runWaterList);
//        // 营业额
//        rm.put("turnoverList",turnoverList);
//        // 分佣金额
//        rm.put("sharePriceList",sharePriceList);
//        // 成交单数
//        rm.put("dealNumList",dealNumList);
//        // 消费人数
//        rm.put("buyerNumList",buyerNumList);
//        // 日期
//        rm.put("dayList",dayList);
//        return AjaxResult.success(rm);
//    }
//
//    /**
//     * 分销商列表查看总流水
//     *
//     * @param
//     * @return 单条数据
//     */
//    @GetMapping("/retailerList/seeRunWater")
//    public ApiResult seeRunWater(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
//                                  @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
//                                  Long userId) {
//        if (userId == null) {
//            return ApiResult.error("缺少用户ID");
//        }
//        try{
//            HashMap<String, Object> map = new HashMap<>();
//            PageHelper.startPage(pageNum,pageSize);
//            List<MallTimeOrder> list = mallTimeOrderService.distributorListViewTotalFlow(userId);
//            PageInfo<MallTimeOrder> pageInfo = new PageInfo<>(list);
//            map.put("data", pageInfo);
//            return ApiResult.ok(map);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }
//
//    /**
//     * 分销商列表查看下级
//     *
//     * @param
//     * @return 单条数据
//     */
//    @GetMapping("/retailerList/seeSubordinate")
//    public ApiResult seeSubordinate(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
//                                 @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
//                                 Long userId) {
//        if (userId == null) {
//            return ApiResult.error("缺少用户ID");
//        }
//        try{
//            HashMap<String, Object> map = new HashMap<>();
//            PageHelper.startPage(pageNum,pageSize);
//            List<MallTimeOrder> list = mallTimeOrderService.distributorListViewSubordinate(userId);
//            PageInfo<MallTimeOrder> pageInfo = new PageInfo<>(list);
//            map.put("data", pageInfo);
//            return ApiResult.ok(map);
//        }catch (Exception e){
//            return ApiResult.error("服务器网络异常");
//        }
//    }

}
